<?php

declare(strict_types=1);

namespace App\Goods\Model;

use App\Lib\Library\Helper;
use Mine\MineModel;

/**
 * @property int $id 记录ID
 * @property string $goods_sku_id 商品sku唯一标识 (由规格id组成)
 * @property int $goods_id 商品ID
 * @property int $image_id 规格图片ID
 * @property string $goods_sku_no 商品sku编码
 * @property string $goods_price 商品价格
 * @property string $line_price 商品划线价
 * @property int $stock_num 当前库存数量
 * @property float $goods_weight 商品重量(Kg)
 * @property string $goods_props SKU的规格属性(json格式)
 * @property string $spec_value_ids 规格值ID集(json格式)
 * @property int $store_id 商城ID
 * @property int $create_time 创建时间
 * @property int $update_time 更新时间
 */
class GoodsSku extends MineModel
{
    protected ?string $dateFormat = 'U';
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'goods_sku';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'goods_sku_id', 'goods_id', 'image_id', 'goods_sku_no', 'goods_price', 'line_price', 'stock_num', 'goods_weight', 'goods_props', 'spec_value_ids', 'store_id', 'create_time', 'update_time'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'goods_id' => 'integer', 'image_id' => 'integer', 'goods_price' => 'decimal:2', 'line_price' => 'decimal:2', 'stock_num' => 'integer', 'goods_weight' => 'float', 'store_id' => 'integer', 'create_time' => 'integer', 'update_time' => 'integer'];

    /**
     * 获取总库存
     * @param $skuList
     * @return void
     */
    public static function getStockTotal($skuList)
    {
        $sum = 0;
        foreach ($skuList as $item) {
            $sum = Helper::bcadd($sum, $item['stock_num']);
        }
        return $sum;
    }


    /**
     * 获取产品最高价与最低价
     * @param $skuList
     * @return void
     */
    public static function getGoodsPrices($skuList)
    {
        $goodsPriceArr = self::getArrayColumn($skuList, 'goods_price');
        return empty($goodsPriceArr) ? [0, 0] : [min($goodsPriceArr), max($goodsPriceArr)];
    }

    /**
     * 获取划线最高价与最低价
     * @param $skuList
     * @return void
     */
    public static function getLinePrices($skuList)
    {
        $linePriceArr = self::getArrayColumn($skuList, 'line_price');
        return empty($linePriceArr) ? [0, 0] : [min($linePriceArr), max($linePriceArr)];
    }

    public static function getArrayColumn($source, $column): array
    {
        $columnArr = [];
        foreach ($source as $item) {
            isset($item[$column]) && $columnArr[] = $item[$column];
        }
        return $columnArr;
    }

    public static function getNewSkuList(array $newSpecList, array $skuList): array
    {
        foreach ($skuList as &$skuItem) {
            $skuItem['specValueIds'] = static::getSpecValueIds($newSpecList, $skuItem['skuKeys']);
            $skuItem['goodsProps'] = static::getGoodsProps($newSpecList, $skuItem['skuKeys']);
            $skuItem['goods_sku_id'] = implode('_', $skuItem['specValueIds']);
        }
        return $skuList;
    }

    private static function getGoodsProps(array $newSpecList, array $skuKeys): array
    {
        $goodsPropsArr = [];
        foreach ($skuKeys as $skuKey) {
            $groupItem = Helper::arraySearch($newSpecList, 'key', $skuKey['groupKey']);
            $specValueItem = Helper::arraySearch($groupItem['valueList'], 'key', $skuKey['valueKey']);
            $goodsPropsArr[] = [
                'group' => ['name' => $groupItem['spec_name'], 'id' => $groupItem['spec_id']],
                'value' => ['name' => $specValueItem['spec_value'], 'id' => $specValueItem['spec_value_id']]
            ];
        }
        return $goodsPropsArr;
    }

    private static function getSpecValueIds(array $newSpecList, array $skuKeys): array
    {
        $goodsSkuIdArr = [];
        foreach ($skuKeys as $skuKey) {
            $groupItem = Helper::arraySearch($newSpecList, 'key', $skuKey['groupKey']);
            $specValueItem = Helper::arraySearch($groupItem['valueList'], 'key', $skuKey['valueKey']);
            $goodsSkuIdArr[] = $specValueItem['spec_value_id'];
        }
        return $goodsSkuIdArr;
    }

    public static function add(int $goodsId, int $specType = 10, array $newSkuList = [], int $storeId = null)
    {
        // 单规格模式
        if ($specType === 10) {
            return self::query()->save(array_merge($newSkuList, [
                'goods_id' => $goodsId,
                'goods_sku_id' => 0,
                'store_id' => empty($storeId) ? 0 : $storeId
            ]));
        } // 多规格模式
        elseif ($specType === 20) {
            // 批量写入商品sku记录
            return static::increasedFroMulti($goodsId, $newSkuList, $storeId);
        }
        return false;
    }

    private static function increasedFroMulti(int $goodsId, array $skuList, int $storeId = null)
    {
        $dataset = [];
        foreach ($skuList as $skuItem) {
            $dataset[] =  [
                //'id' => null,   // 此处的id必须是数据库自增
                'image_id'=>$skuItem['image_id'],
                'goods_sku_id' => $skuItem['goods_sku_id'],
                'goods_price' => $skuItem['goods_price'] ?: 0.01,
                'line_price' => $skuItem['line_price'] ?: 0.00,
                'goods_sku_no' => $skuItem['goods_sku_no'] ?: '',
                'stock_num' => $skuItem['stock_num'] ?: 0,
                'goods_weight' => $skuItem['goods_weight'] ?: 0,
                'goods_props' =>json_encode( $skuItem['goodsProps'],JSON_UNESCAPED_UNICODE),
                'spec_value_ids' => json_encode($skuItem['specValueIds'],JSON_UNESCAPED_UNICODE),
                'goods_id' => $goodsId,
                'store_id' => empty($storeId) ? 0 : $storeId,
                'create_time' => time(),
                'update_time' => time()
            ];//);
        }
        return self::query()->insert($dataset);
    }
}
